﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Leo.Awesome.AppPlatform.Domain;
using Leo.Awesome.AppPlatform.Enums;
using Leo.Awesome.AppPlatform.Repostories;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Guids;
using Volo.Abp.MultiTenancy;
using Volo.Abp.PermissionManagement;

namespace Leo.Awesome.AppPlatform.DomainServices
{
    public class DefaultAdminPermissionDataSeeder : MenuDataSeeder
    {
        private readonly IMenuRepository menuRepository;
        private readonly IPermissionDefinitionManager permissionDefinitionManager;
        private readonly ICurrentTenant currentTenant;
        private readonly IPermissionGrantRepository permissionGrantRepository;
        private readonly IGuidGenerator guidGenerator;

        public DefaultAdminPermissionDataSeeder(
            IMenuRepository MenuRepository,
            IPermissionDefinitionManager  permissionDefinitionManager,
            ICurrentTenant currentTenant,
            IPermissionGrantRepository permissionGrantRepository,
            IGuidGenerator guidGenerator) 
            : base(MenuRepository)
        {
            menuRepository = MenuRepository;
            this.permissionDefinitionManager = permissionDefinitionManager;
            this.currentTenant = currentTenant;
            this.permissionGrantRepository = permissionGrantRepository;
            this.guidGenerator = guidGenerator;
        }

        public override async Task SeedAsync(List<Menu> Menus, string domain = "default")
        {
            await base.SeedAsync(Menus, domain);
            var buttons = await menuRepository.GetListAsync(x => x.MenuType
            == MenuType.Button);
            if (!buttons.Any())
            {
                return;
            }
            var permissions = buttons.Select(x => x.Permission).Distinct().ToList();

            var permissionGrantsFromDb = await permissionGrantRepository
                .GetListAsync(permissions.ToArray(),
                 RolePermissionValueProvider.ProviderName, "admin");

            var existsPermissionGrants = permissionGrantsFromDb.Select(x => x.Name)
                .ToList();

            foreach (var permissionName in permissions.Except(existsPermissionGrants))
            {
                await permissionGrantRepository.InsertAsync(
                new PermissionGrant(
                        guidGenerator.Create(),
                        permissionName,
                        RolePermissionValueProvider.ProviderName,
                        "admin",
                        currentTenant.Id
                    )
                );
            }
        }
    }
}
